import { initData } from '@/api/data'

export default {
  data() {
    return {
      loading: true,
      data: [],
      currentPage: 0,
      size: 10,
      totalCount: 0,
      url: '',
      params: {},
      query: {},
      time: 170,
      isAdd: false,
      tableHeight: ''
    }
  },
  methods: {
    async initPageData() {
      if (!await this.beforeInit()) {
        return
      }
      return new Promise((resolve, reject) => {
        this.loading = true
        this.params['page'] = this.currentPage
        this.params['size'] = this.size
        initData(this.url, this.params).then(res => {
          this.totalCount = res.data.totalCount
          this.data = res.data.dataList
          setTimeout(() => {
            this.loading = false
          }, this.time)
          resolve(res)
        }).catch(err => {
          this.loading = false
          reject(err)
        })
      })
    },
    async initAllData() {
      if (!await this.beforeInit()) {
        return
      }
      return new Promise((resolve, reject) => {
        this.loading = true
        initData(this.url, this.params).then(res => {
          this.data = res.data
          setTimeout(() => {
            this.loading = false
          }, this.time)
          resolve(res)
        }).catch(err => {
          this.loading = false
          reject(err)
        })
      })
    },
    beforeInit() {
      return true
    },
    pageChange(e) {
      this.currentPage = e - 1
      this.initPageData()
    },
    sizeChange(e) {
      this.currentPage = 0
      this.size = e
      this.initPageData()
    },
    // 预防删除第二页最后一条数据时，或者多选删除第二页的数据时，页码错误导致请求无数据
    dleChangePage(size) {
      if (size === undefined) {
        size = 1
      }
      if (this.data.length === size && this.currentPage !== 0) {
        this.currentPage = this.currentPage - 1
      }
    },
    toPageQuery() {
      this.currentPage = 0
      this.initPageData()
    },
    toQuery() {
      this.currentPage = 0
      this.initAllData()
    },
    resetSearchData() {
      // 重置查询框
      this.$refs['formSearch'].resetFields()
    },
    setHeight() {
      // 调整页面高度
      this.tableHeight = window.innerHeight - 250
      if (this.tableHeight > 850) {
        this.size = 20
      }
    }
  }
}
